import { getArticles, getArticlesRefresh } from '@/store/actions/home'
import { RootState } from '@/types/store'
import { InfiniteScroll, PullToRefresh } from 'antd-mobile'
import { useDispatch, useSelector } from 'react-redux'
import ArticleItem from '../ArticleItem'
import styles from './index.module.scss'

type Props = {
  channelId: number
}

const ArticleList = ({ channelId }: Props) => {
  const dispatch = useDispatch()
  const { channelArticles } = useSelector((state: RootState) => state.home)

  const { timestamp, articles = [] } = channelArticles[channelId] || {}

  const hasMore = timestamp === null ? false : true
  // loadMore一开始书记为空,自动发送一次请求
  // 1.进入页面执行一次
  // 2.触底了,还会触发
  const loadMore = async () => {
    await dispatch(getArticles(channelId, timestamp || +new Date() + ''))
  }

  return (
    <div className={styles.root}>
      <PullToRefresh
        onRefresh={async () => {
          // 重新发送请求,获取最新的数据,传到当前的时间戳
          await dispatch(getArticlesRefresh(channelId, +new Date() + ''))
        }}
      >
        {/* 文章列表中的每一项 */}
        {articles.map((item) => (
          <div className="article-item" key={item.art_id}>
            <ArticleItem article={item} />
          </div>
        ))}

        {/* 触底加载更多 */}
        <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
      </PullToRefresh>
    </div>
  )
}

export default ArticleList
